package cn.edu.stu.contorller.system;

import cn.edu.stu.bean.AjaxResult;
import cn.edu.stu.bean.MicUser;
import cn.edu.stu.service.ConfService;
import cn.edu.stu.service.UserService;
import cn.edu.stu.tool.Constants;
import cn.edu.stu.tool.JWTUtil;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * @author Karl
 * @Date 2022/12/11 - 22:55
 */
@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    ConfService confService;

    @Autowired
    UserService userService;


    @PostMapping("/login")
    public AjaxResult verifyLogin(@RequestParam("act") String userAct,
                                  @RequestParam("psw") String password,
                                  @RequestParam(value = "code", required = false) String code,
                                  @RequestParam(value = "isWeb", required = false) boolean isWeb,
                                  HttpServletRequest request, HttpServletResponse response) {
        //系统需要验证码登录
        if (confService.selectCaptchaOnOff()) {
            AjaxResult result = validateCaptcha(code, request);
            if (result != null) return result;
        }
        AjaxResult result = userService.login(userAct, password);
        if (isWeb) {
            Cookie cookie = new Cookie("token", (String) result.getData("token"));
            cookie.setMaxAge(confService.getExpirationTime());
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return result;

    }

    @PostMapping("/register")
    public AjaxResult registerUser(@RequestParam("act") String userAct,
                                   @RequestParam("psw") String password,
                                   @RequestParam(value = "code", required = false) String code,
                                   @RequestParam("uid") Long uid,
                                   @RequestParam("name") String name,
                                   HttpServletRequest request) {
        //系统需要验证码登录
        if (confService.selectCaptchaOnOff()) {
            AjaxResult result = validateCaptcha(code, request);
            if (result != null) return result;
        }
        MicUser user = new MicUser();
        user.setUserAct(userAct);
        user.setUserId(uid);
        user.setUserPsw(password);
        user.setUserName(name);
        return userService.register(user);
    }

    //校验验证码
    private AjaxResult validateCaptcha(String code, HttpServletRequest request) {
        if (code == null) return AjaxResult.error("验证码为空！请输入验证码！");
        String token = request.getHeader("token");

        if (token == null)
            return AjaxResult.error("请先点击获取验证码！");
        Map<String, String> verify = null;
        try {
            verify = JWTUtil.verify(token);
        } catch (TokenExpiredException ex) {
            return AjaxResult.error("验证码过期，请重新获取验证码！");
        } catch (Exception e) {
            return AjaxResult.error("令牌错误！");
        }
        String realCode = verify.get(Constants.CAPTCHA_CODE_KEY);
        if (!code.toLowerCase().equals(realCode)) {
            return AjaxResult.error("验证码错误！");
        }
        return null;
    }
}
